<template>
  <div class="cell-data">
    <!-- 标题 -->
    <div class="page-title">
      <div v-if="active === 'list'">{{functionName}}信息管理</div>
      <el-breadcrumb separator="/" v-if="active !== 'list'">
        <el-breadcrumb-item :to="{ path: '/' + model }">{{functionName}}信息管理</el-breadcrumb-item>
        <el-breadcrumb-item v-if="active === 'count'">{{ functionName }}统计</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card class="clearfix">
      <div slot="header">
        <el-row class="tab" :gutter="20" type="flex" justify="space-between" align="middle">
          <el-col :span="18">
            <el-tabs v-model="active" @tab-click="tableChange">
              <el-tab-pane name="list">
                <span slot="label"><i class="el-icon-search"></i> 查看{{ functionName }}</span>
              </el-tab-pane>
              <el-tab-pane name="count">
                <span slot="label"><i class="el-icon-information"></i> {{ functionName }}统计</span>
              </el-tab-pane>
            </el-tabs>
          </el-col>
          <el-col :span="6">
            <el-button class="submit" type="primary" @click="handleCreate" :plain="true"
                       size="small"
                       icon="plus">新建
            </el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 搜索 -->
      <div class="search-panel" v-if="active === 'list'">
        <el-col :span="8">
          <el-autocomplete
            placeholder="请输入内容"
            icon="search"
            v-model="searchValue"
            :fetch-suggestions="querySearchAsync"
            :on-icon-click="handleSearch">
            <el-select v-model="filter.key" slot="prepend" placeholder="请选择"
                       @change="searchValue = ''">
              <el-option label="分类名称" value="name" v-if="model !== 'family'"></el-option>
              <el-option label="分类详情" value="desc"></el-option>
              <el-option v-if="model === 'family'" label="户主姓名" value="name"></el-option>
            </el-select>
          </el-autocomplete>
        </el-col>
      </div>
      <!-- list数据展示 -->
      <div v-if="active === 'list'" class="list">
        <!-- tag -->
        <el-table
          v-loading="loading"
          :data="tableData">
          <!-- name -->
          <el-table-column
            prop="name"
            :label="functionName + '名称'"
            min-width="120">
          </el-table-column>

          <!--<el-table-column-->
            <!--v-if="model === 'family'"-->
            <!--label="所属分类"-->
            <!--min-width="120">-->
            <!--<template scope="scope">-->
              <!--<el-button type="text" size="small">{{ scope.row.tag || '暂无' }}</el-button>-->
            <!--</template>-->
          <!--</el-table-column>-->

          <!-- count -->
          <el-table-column
            label="人数"
            min-width="80">
            <template scope="scope">
              {{ scope.row.count || 0 }}
            </template>
          </el-table-column>

          <!-- desc -->
          <el-table-column
            label="详情"
            min-width="160">
            <template scope="scope">
              <label
                v-if="scope.row.desc.length < 18"> {{ scope.row.desc || '暂无' }} </label>

              <!-- hover显示 -->
              <el-button
                v-if="scope.row.desc.length > 8"
                v-popover:detiles
                type="text"
                size="small">
                查看
                <el-popover
                  ref="detiles"
                  placement="top-start"
                  title="详情"
                  trigger="hover"
                  :content="scope.row.desc">
                </el-popover>
              </el-button>
            </template>
          </el-table-column>

          <!-- creator -->
          <el-table-column
            label="创建人"
            width="80">
            <template scope="scope">
              {{ scope.row.creator.username || '暂无' }}
            </template>
          </el-table-column>

          <!-- createdAt -->
          <el-table-column
            label="创建时间"
            min-width="110">
            <template scope="scope">
              {{ scope.row.createdAt | dateformat }}
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            fixed="right"
            min-width="100">
            <template scope="scope">
              <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" :disabled="scope.row.count > 0"
                         @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          small
          layout="prev, pager, next"
          :current-page.sync="page.currentPage"
          :page-size="page.pageSize"
          :total="page.total"
          @current-change="handleCurrentChange">
        </el-pagination>

      </div>
      <!-- 新建 & 编辑 -->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="createView"
        :title="'新建' + functionName">
        <div class="new-panel">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
            <el-row :gutter="20">
              <el-col :span="24" v-if="model !== 'family'">
                <el-form-item :label="functionName + '名称'" prop="name">
                  <el-input v-model="form.name" size="small" @blur="checkExists"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="model === 'family'">
                <el-form-item label="户主" prop="name">
                  <el-select
                    size="small"
                    v-model="form.name"
                    filterable
                    remote
                    @change="selectHostId"
                    style="width: 100%;"
                    placeholder="请输入姓或名搜索"
                    :remote-method="loadName"
                    :loading="loadingName">
                    <el-option
                      v-for="item in loadNameData"
                      :key="item._id"
                      :label="item.username"
                      :value="item.username">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="model === 'family'">
                <el-form-item label="家庭类别" prop="tag">
                  <el-select size="small" style="width: 100%"
                             v-model="form.tag"
                             multiple
                             placeholder="请选择">
                    <el-option
                      v-for="item in tagData"
                      :key="item._id"
                      :label="item.name"
                      :value="item._id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="详细信息">
                  <el-input v-model="form.desc"
                            :disabled="viewView"
                            type="textarea"
                            placeholder="如分类说明，记账规则等"
                            :rows="4"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-button type="primary" @click="submit('form')" class="submit" size="small"
                           :disabled="loading">
                  {{ editView ? '提交修改' : '创建' }}
                </el-button>
                <el-button type="text" size="small" class="submit error">{{ error.info }}
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
  import {httpGet, httpPost, httpPut, httpDelete} from '../util/api'

  export default {
    name: 'cell-data',
    data() {
      return {
        error: {
          info: '',
        },
        viewView: false,
        tagData: [], // 分类
        createView: false,
        editView: false,
        loadingName: false,
        loadNameData: [],
        loading: false,
        active: 'list', // new count
        functionName: '分类',
        model: 'tag', // 当前数据模型
        searchValue: '', // 搜索关键字
        searchTemp: [],
        searchView: false,
        form: {
          name: '',
          user: '',
          desc: '',
          tag: [], // 家庭分类
        },
        filter: {
          key: 'name',
        },
        timeout: 0,
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          totalPage: 0,
        },
        rules: {
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' },
          ],
          tag: [
            { required: true, type: 'array', message: '请选择类别', trigger: 'blur' },
          ],
        },
        tableData: [{
          name: '',
          creator: '',
          createdAt: '',
          desc: '',
          user: {
            username: '',
          }
        }],
      }
    },
    computed: {
      handleTable() {
        if (this.active === 'list') {
          return this.model
        } else {
          return ''
        }
      },
    },
    created() {
      this.init()
    },
    watch: {
      $route: 'init',
    },
    methods: {
      selectHostId(row) {
        let user = this.loadNameData
        user = user.filter((item) => {
          return item.username === row
        })
        this.form.user = user[0]._id
      },
      // 提交创建
      submit(formName) {
        if (this.error.info) {
          this.$message.error(this.error.info)
          return
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true
            httpPost(`/cell/${this.model}`, this.form).then((response) => {
              const data = response.data
              this.$message.success('创建成功')
              this.loading = false
              this.loadData()
              this.createView = false
            }).catch((e) => {
              this.$message.error('网络错误')
              this.loading = false
            })
            /*
            if (this.editView) {
              httpPut(`/cell/${this.model}`, this.form).then((response) => {
                const data = response.data
                this.$message.success('更新成功')
                this.loading = false
                this.loadData()
              })
            } else {
            } */
          } else {
            return false
          }
        })
      },
      init() {
        this.form = {
          name: '',
          user: '',
          desc: '',
          tag: '',
        }
        let oper = this.$route.query.oper || 'list'
        oper = ['list', 'count'].includes(oper) ? oper : 'list'
        this.active = oper
        this.functionName = this.$route.name.slice(0, 2)
        switch (this.functionName) {
          case '分类':
            this.model = 'tag'
            break
          case '补助':
            this.model = 'allowance'
            break
          case '家庭':
            this.model = 'family'
            break
          default:
            this.model = 'tag'
            break
        }
        // 重置页码
        this.page = {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          totalPage: 0,
        }
        // 重置searchValue
        this.searchValue = ''
        this.loadData()
      },
      // 加载数据
      loadData() {
        if (this.active === 'list') {
          if (this.model === 'family') {
            httpGet('/cell/tag').then((response) => {
              this.tagData = response.data.result.data
            })
          }
          // 加载全部 List 表格数据 ( filter = {} )
          const url = `/cell/${this.model}?currentPage=${this.page.currentPage}&pageSize=${this.page.pageSize}`
          this.loading = true
          httpGet(url).then((response) => {
            const data = response.data.result
            this.page.currentPage = data.currentPage || 1
            this.pageSize = data.pageSize || 10
            this.total = data.total || 0
            this.tableData = data.data
            this.loading = false
            this.viewView = false
            this.createView = false
            this.editView = true
          }).catch((e) => {
            this.loading = false
          })
          this.form = {
            name: '',
            user: '',
            desc: '',
            tag: '',
          }
        }
        // 加载新建框
        else {
          // 加载统计
        }
      },
      handleCreate() {
        this.editView = false
        this.createView = true
      },
      // 编辑分类
      handleEdit(row) {
        this.editView = true
        this.createView = true
        this.viewView = false
        this.form = row
      },
      handleView(row) {
        this.createView = true
        this.viewView = true
        this.form = row
      },
      // 删除数据
      handleDelete(row) {
        httpDelete(`/cell/${this.model}/${row._id}`).then((response) => {
          if (response.data.code === 200) {
            this.$message.success('删除成功')
            this.loadData()
          }
        })
      },
      // 切换页面
      handleCurrentChange(nth) {
        this.loadData()
      },
      // 搜索构造器
      handlerQuery(isWant = true) {
        let filter = {}
        filter[this.filter.key] = `^${this.searchValue}`
        let want = {}
        want[this.filter.key] = 1
        if (isWant) {
          return `/cell/${this.model}?filter=${JSON.stringify(filter)}&want=${JSON.stringify(want)}`
        } else {
          filter[this.filter.key] = `${this.searchValue}`
          return `/cell/${this.model}?filter=${JSON.stringify(filter)}`
        }
      },
      // 检查存在
      checkExists() {
        if (!this.form.name || this.editView) {
          return
        }
        httpGet(`/cell/${this.model}?single=true&filter=${JSON.stringify({ name: this.form.name })}`).then((response) => {
          const data = response.data
          if (data.result._id) {
            this.error.info = '名称已存在'
          } else {
            this.error.info = ''
          }
        })
      },
      //远程搜索
      querySearchAsync(key, cb) {
        if (!key) {
          return cb([])
        }
        // 清除定时器
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          console.log('开始')
          httpGet(this.handlerQuery()).then((response) => {
            const data = response.data
            // 组织 { value: xxxx }
            if (data.code === 200) {
              let result = []
              data.result.data.forEach((item) => {
                if (item[this.filter.key]) {
                  result.push({ value: item[this.filter.key] })
                }
              })
              cb(result)
            } else {
              cb([])
            }
          }).catch((e) => {
            cb([])
            console.log(e)
          })
        }, 800)
      },
      // 开始搜索
      handleSearch() {
        if (!this.searchValue) {
          return this.$message.error('请输入关键字搜索')
        }
        // 重置页码
        this.page = {
          currentPage: 1,
          pageSize: 20,
          total: 0,
          totalPage: 0,
        }
        httpGet(this.handlerQuery(false)).then((response) => {
          this.searchView = true
          this.loading = true
          const data = response.data.result
          this.tableData = data.data
          // 页码回归
          this.page = {
            currentPage: data.currentPage,
            pageSize: data.pageSize,
            total: data.total,
            totalPage: data.totalPage,
          }
          this.loading = false
        }).catch((e) => {
          console.log(e)
          this.loading = false
        })
      },
      // tab切换 切换路由
      tableChange() {
        this.$router.push({ path: `/${this.model}`, query: { oper: this.active } })
      },
      // 创建 -- 远程搜索
      loadName(query = '') {
        clearInterval(this.timeout)
        if (!query) {
          return
        }
        this.loadingName = true
        let queryString = ''
        if (this.model === 'family') {
          const filter = { username: `^${query}` }
          const want = { username: 1 }
          queryString = `/user?filter=${JSON.stringify(filter)}&want=${JSON.stringify(want)}`
        } else {
          let filter = {}
          filter[this.model] = `^${this.query}`
          queryString = `/cell/${this.model}?filter=${JSON.stringify(filter)}`
        }
        this.timeout = setTimeout(() => {
          httpGet(queryString).then((response) => {
            this.loadingName = false
            this.loadNameData = response.data.result.data
          })
        }, 200)
      },
    },
  }
</script>


<style lang="scss">
  .cell-data {
    .submit {
      min-width: 80px;
      float: right;
      &.error {
        margin-right: 20px;
        color: #ff6936;
      }
    }
    .tab {
      &.el-row {
        height: 60px;
      }
      .el-tabs__header {
        margin: 0;
        height: 60px;
        border: none;
      }
      .el-tabs__item {
        height: 60px;
        line-height: 60px;
      }
      // border
      .el-tabs__active-bar {
        height: 2px;
      }
    }
    .el-card .el-card__header {
      padding: 0 20px !important;
    }
    .el-table {
      width: 100%;
    }

    .el-form {
      margin-top: 32px;
    }

    .el-pagination {
      float: right;
      margin: 24px auto;
    }

    .list {
      width: 100%;
      margin-top: 64px;
    }
    .el-dialog__body {
      padding: 10px auto;
    }
    .search-panel {
      float: right;
      margin: 24px auto;
      .el-autocomplete {
        width: 380px;
      }
      .el-select {
        width: 120px;
      }
    }
  }
</style>
